/**
 * 
 */
package fr.sportsurbains.tools;

import java.io.ByteArrayOutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * @author jshi
 *
 */
public class DBManager {
	private DBHelper helper;
	private SQLiteDatabase db;
	
	public DBManager(Context context) {
		helper = new DBHelper(context);
		db = helper.getWritableDatabase();
	}
	/*
	public List<Map<String,String>> getTopicsByCategory(String category) {
		category = TextUtils.join("_", category.split("-"));
		Cursor c = db.rawQuery("SELECT * from "+category+" ORDER BY date DESC",null);
		List<Map<String,String>> topics = new ArrayList<Map<String,String>>();
		if(c.getCount() > 0) {
			c.moveToFirst();
			do {
				Map<String,String> topic = new HashMap<String,String>();
				topic.put("title", c.getString(c.getColumnIndex("title")));
				topic.put("image", c.getString(c.getColumnIndex("image")));
				topic.put("summary", c.getString(c.getColumnIndex("summary")));
				topic.put("link", c.getString(c.getColumnIndex("link")));
				if((!category.equals("info_en_continu"))&&(!category.equals("video"))) {
					topic.put("id", c.getString(c.getColumnIndex("_id")));
					topic.put("date", c.getString(c.getColumnIndex("date")));
				}
				topics.add(topic);
			} while(c.moveToNext());
		}
		return topics;
		
	}
	
	public List<Map<String,String>> getTopicsByCategory(String category, int count) {
		category = TextUtils.join("_", category.split("-"));
		Cursor c = db.rawQuery("SELECT * from "+category+" ORDER BY date DESC "+"limit 0,"+String.valueOf(count),null);
		List<Map<String,String>> topics = new ArrayList<Map<String,String>>();
		if(c.getCount() > 0) {
			c.moveToFirst();
			do {
				Map<String,String> topic = new HashMap<String,String>();
				topic.put("title", c.getString(c.getColumnIndex("title")));
				topic.put("image", c.getString(c.getColumnIndex("image")));
				topic.put("summary", c.getString(c.getColumnIndex("summary")));
				topic.put("link", c.getString(c.getColumnIndex("link")));
				if((!category.equals("info_en_continu"))&&(!category.equals("video"))) {
					topic.put("id", c.getString(c.getColumnIndex("_id")));
					topic.put("date", c.getString(c.getColumnIndex("date")));
				}
				topics.add(topic);
			} while(c.moveToNext());
		}
		return topics;
		
	}*/
	
	public Bitmap getBitmapFromUrl(String url) {
		Cursor c = db.rawQuery("SELECT bitmap FROM images WHERE link = ?;",new String[] {url});
		Bitmap bmout = null;
		if(c.getCount() > 0) {
			byte[] in = c.getBlob(c.getColumnIndex("bitmap"));
			bmout = BitmapFactory.decodeByteArray(in, 0, in.length);
		}
		return bmout;
	}
	
	/**
	 * add topics by category, return the count of no duplicate topics
	 * @param topics
	 * @param category
	 * @return
	 *//*
	public int addTopics(List<Map<String,String>> topics,String category) {
		category = TextUtils.join("_", category.split("-"));
		int count = 0;
		for(Map<String,String> topic:topics) {
			Cursor c = db.rawQuery("SELECT * FROM "+category+" WHERE _id=?",new String[] {topic.get("id")});
			if(c.getCount() == 0) {
				count++;
				ContentValues cv = new ContentValues();
				cv.put("_id", topic.get("id"));
				cv.put("title", topic.get("title"));
				cv.put("image", topic.get("image"));
				cv.put("summary", topic.get("summary"));
				cv.put("date", topic.get("date"));
				cv.put("link", topic.get("link"));
				db.beginTransaction();  //开始事务  
		        try {  
	                //db.execSQL("INSERT INTO "+category+" VALUES(?, ?, ?, ?, ?, ?)", new Object[]{topic.get("id"), topic.get("title"), topic.get("summary"),topic.get("image"),topic.get("date"),topic.get("link")});
		        	db.insert(category, null, cv);
		            db.setTransactionSuccessful();  //设置事务成功完成  
		        } finally {  
		            db.endTransaction();    //结束事务  
		        }  
			}
		}
		return count;
	}
	
	public int addInfoEnContinu(List<Map<String,String>> infos) {
		int count = 0;
		for(Map<String,String> info:infos) {
			Cursor c = db.rawQuery("SELECT * FROM info_en_continu WHERE title=?",new String[] {info.get("title")});
			if(c.getCount() == 0) {
				count++;
				ContentValues cv = new ContentValues();
				cv.put("title", info.get("title"));
				cv.put("image", info.get("image"));
				cv.put("summary", info.get("summary"));
				cv.put("link", info.get("link"));
				db.beginTransaction();  //开始事务  
		        try {  
		        	db.insert("info_en_continu", null, cv);
		            db.setTransactionSuccessful();  //设置事务成功完成  
		        } finally {  
		            db.endTransaction();    //结束事务  
		        }  
			}
		}
		return count;
	}
	
	public int addVideos(List<Map<String,String>> videos) {
		int count = 0;
		for(Map<String,String> video:videos) {
			Cursor c = db.rawQuery("SELECT * FROM video WHERE title=?",new String[] {video.get("title")});
			if(c.getCount() == 0) {
				count++;
				ContentValues cv = new ContentValues();
				cv.put("title", video.get("title"));
				cv.put("image", video.get("image"));
				cv.put("summary", video.get("summary"));
				cv.put("link", video.get("link"));
				db.beginTransaction();  //开始事务  
		        try {  
		        	db.insert("video", null, cv);
		            db.setTransactionSuccessful();  //设置事务成功完成  
		        } finally {  
		            db.endTransaction();    //结束事务  
		        }  
			}
		}
		return count;
	}*/
	/**
	 * add a bitmap with its url, return its id of row in the database
	 * @param url
	 * @param bp
	 * @return
	 */
	public Long addBitmap(String url, Bitmap bp) {
		ContentValues cv = new ContentValues();
		Long id = null;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		bp.compress(Bitmap.CompressFormat.PNG, 100, os);
		cv.put("bitmap", os.toByteArray());
		id = db.insert("images", null, cv);
		return id;
	}
	
	public void closeDB() {
		db.close();
	}

}
